import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { NavController, AlertController } from '@ionic/angular';
import { HttpService } from '../../../service/http.service';
import { ToastService } from '../../../service/toast.service';
import { TranslateService } from '@ngx-translate/core';

@Component({
    selector: 'app-patient-person-edit',
    templateUrl: './patient-person-edit.page.html',
    styleUrls: ['./patient-person-edit.page.scss'],
})
export class PatientPersonEditPage implements OnInit {
    aType = '';
    aValue = '';
    sexBox = [{ code: '1', value: '男' }, { code: '2', value: '女' }];
    selectSex: '';
    personName = '';
    personSex = '';
    personAge = '';
    personDD = '';
    verifyCode: any = {
        verifyCodeTips: 'GetCode',
        countdown: 300,
        disable: true,
    };
    newTel = '';
    phoneCode = '';
    aUserId = '';
    patientBirthday = '';

    phoneNum = '';
    password = '';
    confirm = '';
    sysLang = '';
    codeArr: any[] = [
        '1',
        '86',
        '81',
        '66',
        '852',
        '886'
    ];
    countryCode = '';
    constructor(
        private activatedRoute: ActivatedRoute,
        private toastSrv: ToastService,
        public alertController: AlertController,
        private httpService: HttpService,
        public nav: NavController,
        private translate: TranslateService,
    ) {
        this.activatedRoute.queryParams.subscribe(queryParams => {
            if (!!queryParams.dataType) {
                this.aType = queryParams.dataType;
            }

            if (!!queryParams.value) {
                this.aValue = queryParams.value;
            }
        });
    }

    ngOnInit() {
        this.aUserId = localStorage.getItem('userId');
        this.sysLang = this.translate.getBrowserCultureLang().toLowerCase();
    }

    savePatient() {
        const self = this;
        if (this.aType === 'name') {
            this.saveData('nickname', self.aValue);
        } else if (this.aType === 'englishName') {
            this.saveData('englishName', self.aValue);
        } else if (this.aType === 'passport') {
            this.saveData('passport', self.aValue);
        } else if (this.aType === 'sex') {
            this.saveData('gender', self.aValue);
        } else if (this.aType === 'age') {
            this.saveData('birthday', self.aValue);
        } else if (this.aType === 'phone') {
            this.changePhoneNum();
        } else if (this.aType === 'email') {
            this.saveData('email', self.aValue);
        } else if (this.aType === 'MH') {
            this.saveData('medical_history', self.aValue);
        } else if (this.aType === 'DD') {
            this.saveData('medical_desc', self.aValue);
        }
    }

    public settime() {
        if (this.verifyCode.countdown === 1) {
            this.verifyCode.countdown = 300;
            this.verifyCode.verifyCodeTips = 'GetCode';
            this.verifyCode.disable = true;
            return;
        } else {
            this.verifyCode.countdown--;
        }

        this.verifyCode.verifyCodeTips = (this.sysLang === 'en-us' ? 'Resend(' : '重新获取(') + this.verifyCode.countdown + ')';
        setTimeout(() => {
            this.verifyCode.verifyCodeTips = (this.sysLang === 'en-us' ? 'Resend(' : '重新获取(') + this.verifyCode.countdown + ')';
            this.settime();
        }, 1000);
    }

    public async changePhoneNum() {
        if (this.sysLang === 'en-us') {
            if (!this.aValue) {
                this.toastSrv.showToast('Please Enter Exact Phone Number');
                return;
            }
            if (!this.phoneCode) {
                this.toastSrv.showToast('Please Enter Verification Code');
            }
            if (!this.newTel) {
                this.toastSrv.showToast('Please Enter New Phone Number');
                return;
            } else {
                if (this.aValue === this.newTel) {
                    this.toastSrv.showToast('Please Enter A New Phone Different With Current');
                    return;
                }
            }
        } else {
            if (!this.aValue) {
                this.toastSrv.showToast('请输入正确的手机号码');
                return;
            }
            if (!this.phoneCode) {
                this.toastSrv.showToast('请输入短信验证码');
            }
            if (!this.newTel) {
                this.toastSrv.showToast('请输入新手机号');
                return;
            } else {
                if (this.aValue === this.newTel) {
                    this.toastSrv.showToast('请输入与当前手机号不同的手机号');
                    return;
                }
            }
        }
        const result: any = await this.httpService.put()
            .setPath('/user/modifyIdentity/1')
            .setBody({
                original: this.aValue,
                current: this.newTel,
                verifyCode: this.phoneCode
            })
            .request();
        if (result.status === 0) {
            const aMessage = this.sysLang === 'en-us' ? 'Modify Success' : '修改成功';
            const aText = this.sysLang === 'en-us' ? 'Confirm' : '确定';
            const alert = await this.alertController.create({
                message: aMessage,
                buttons: [
                    {
                        text: aText,
                        handler: () => {
                            this.nav.pop();
                        }
                    }
                ]
            });
            await alert.present();
        }
    }
    public async saveData(aKey, aParam) {
        const postBody = {};
        postBody[aKey] = aParam;
        const result: any = await this.httpService.put()
            .setPath('/user/patientUpdate/' + this.aUserId)
            .setBody({
                ...postBody
            })
            .request();
        if (result.status === 0) {
            const aMessage = this.sysLang === 'en-us' ? 'Save Success' : '保存成功';
            const aText = this.sysLang === 'en-us' ? 'Confirm' : '确定';
            const alert = await this.alertController.create({
                message: aMessage,
                buttons: [
                    {
                        text: aText,
                        handler: () => {
                            // this.nav.navigateRoot('/patient-personal-center');
                            this.nav.pop();
                        }
                    }
                ]
            });
            await alert.present();
        }
    }

    public async getBirthday(event) {
        this.aValue = event.detail.value;
    }

    public async registerIme() {
        if (this.sysLang === 'en-us') {
            if (!this.phoneNum) {
                this.toastSrv.showToast('Please Enter Exact Phone Number');
                return;
            }
            if (!this.phoneCode) {
                this.toastSrv.showToast('Please Enter Verification Code');
                return;
            }
            if (!this.password || this.password.length < 8) {
                this.toastSrv.showToast('Password Must Be At Least 8 Characters');
                return;
            }
            if (!this.confirm || this.confirm.length < 8) {
                this.toastSrv.showToast('Please Enter Confirm Password');
                return;
            } else {
                if (this.password !== this.confirm) {
                    this.toastSrv.showToast('The Two Passwords You Typed Do Not Match');
                    return;
                }
            }
        } else {
            if (!this.phoneNum) {
                this.toastSrv.showToast('请输入正确手机号');
                return;
            }
            if (!this.phoneCode) {
                this.toastSrv.showToast('请输入手机验证码');
                return;
            }
            if (!this.password || this.password.length < 8) {
                this.toastSrv.showToast('请输入至少8位密码');
                return;
            }
            if (!this.confirm || this.confirm.length < 8) {
                this.toastSrv.showToast('请输入确认密码');
                return;
            } else {
                if (this.password !== this.confirm) {
                    this.toastSrv.showToast('两次密码输入不一致');
                    return;
                }
            }
        }
        const userId = localStorage.getItem('userId');
        const result: any = await this.httpService.put()
            .setPath('/user/patientIdentity/' + userId)
            .setBody({
                phone: this.phoneNum,
                verifyCode: this.phoneCode,
                password: this.password,
                confirm: this.confirm
            })
            .request();
        if (result.status === 0) {
            this.nav.navigateRoot('/patient-personal-center');
        }
    }

    public async getPhoneCode() {
        if (!this.countryCode) {
            const aDes = this.sysLang === 'en-us' ? 'Please Enter Country Code (CC)' : '请输入国家代码（CC）';
            this.toastSrv.showToast(aDes);
            return;
        }
        if (!this.phoneNum) {
            const aDes = this.sysLang === 'en-us' ? 'Please Enter Exact Phone Number' : '请输入正确手机号';
            this.toastSrv.showToast(aDes);
            return;
        }
        const result: any = await this.httpService.post()
            .setPath('/pub/user/verifyCode')
            .setBody({
                smsType: 1,
                type: 1,
                phone: this.phoneNum,
                country_code: this.countryCode
            })
            .request();
        if (result.status === 0) {
            if (this.sysLang === 'en-us') {
                const aWord = 'Message Sent';
                this.toastSrv.setDuration(5000).showToast(aWord);
            } else {
                const aWord = '验证码已发送';
                this.toastSrv.setDuration(5000).showToast(aWord);
            }
            if (result.data.expire < 300) {
            } else {
                this.verifyCode.disable = false;
                this.settime();
            }
        }
    }

    public async getCode() {
        if (!this.countryCode) {
            const aDes = this.sysLang === 'en-us' ? 'Please Enter Country Code (CC)' : '请输入国家代码（CC）';
            this.toastSrv.showToast(aDes);
            return;
        }
        if (!this.aValue) {
            const aDes = this.sysLang === 'en-us' ? 'Please Enter Exact Phone Number' : '请输入正确手机号';
            this.toastSrv.showToast(aDes);
            return;
        }
        const result: any = await this.httpService.post()
            .setPath('/pub/user/verifyCode')
            .setBody({
                smsType: 3,
                type: 1,
                phone: this.aValue,
                country_code: this.countryCode
            })
            .request();
        if (result.status === 0) {
            if (this.sysLang === 'en-us') {
                const aWord = 'Message Sent';
                this.toastSrv.setDuration(5000).showToast(aWord);
            } else {
                const aWord = '验证码已发送';
                this.toastSrv.setDuration(5000).showToast(aWord);
            }
            if (result.data.expire < 300) {
            } else {
                this.verifyCode.disable = false;
                this.settime();
            }
        }
    }
}
